package com.fept.msgcore.msgserver.senderinfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Srma on 2/9/2017.
 */
public class ClientManager {
    private Map<String, Client> clients = new ConcurrentHashMap<String, Client>();

    static private Map<String, ClientManager> clientManager = new ConcurrentHashMap<String, ClientManager>();

    /**
     *
     * @param name
     * @return
     */
    static public ClientManager getClientManager(String name) {
        ClientManager mgr = ClientManager.clientManager.get(name);
        if (mgr == null) {
            mgr = new ClientManager();
            ClientManager.clientManager.put(name, mgr);
        }
        return mgr;
    }

    /**
     *
     * @return
     */
    public int getNumberOfConcurrentClients() {
        return this.clients.size();
    }

    /**
     *
     */
    private ClientManager() {
    }

    /**
     * list all online clients
     *
     * @return
     */
    public List<Client> listOnlineClients() {
        List<Client> listClients = new ArrayList<Client>();
        for (Client c : this.clients.values()) {
            listClients.add(c);
        }
        return listClients;
    }

    /**
     *
     * @param c
     */
    public void addClient(Client c) {
        this.clients.put(c.getIp()+":"+c.getPort(), c);
    }

    /**
     *
     * @param key
     * @return
     */
    public Client getClient(String hostIp,int hostPort) {
        return this.clients.get(hostIp+":"+hostPort);
    }

    /**
     *
     * @param key
     */
    public void removeClient(String key) {
        this.clients.remove(key);
    }

    /**
     * 客户端数量
     *
     * @return
     */
    public long countClients() {
        return this.clients.size();
    }
}
